﻿/**
 * 叫注 / 说话 - 一个玩家的决定。德州扑克游戏里共有七种决定
 * 
 */
function gameEvent() { }

/**
 * 調用本類的實例方法
 * @param	r_room	房間對象
 * @param	r_user	操作者
 * @param	r_type	操作類型
 * @param	r_bet	操作籌碼
 * @return	.....
 */
gameEvent.prototype.handleFun = function(r_room, r_user, r_type, r_bet) {			
	if ( r_type != '' ) {
		//trace("function:" + r_type);				
		return this[r_type](r_room, r_user, r_bet);
	}
}


/**
 * 遊戲初始化
 * 實例化撲克類, 去除大鬼、小鬼, 獲取用戶私有牌 與 公共牌	 
 * 
 * @param 　r_room	遊戲房間
 * @return	Array	_result = array([5張公共牌]，[每個玩家的私有牌])
 */
gameEvent.prototype.getRoomPoker = function(r_room) {
	var _poker = new poker();
	var _remove = [ { 'label':'BLACK_JOKER', 'value':0, 'suit':'NULL' }, { 'label':'RED_JOKER', 'value':0, 'suit':'NULL' } ];			
	_poker.remove(_remove);
	_poker.shuffle();
	var _pub_card = _poker.deal(5);//5張公共牌			
	var _player = r_room.getAllPlayers();  //獲取游戲玩家
	var _user_card = [];
	var _user_poker = [			
		[ { 'label':3, 'value':2, 'suit':'DIAMOND' }, { 'label':10, 'value':9, 'suit':'SPADE' } ],
		[ { 'label':3, 'value':2, 'suit':'CLUB' }, { 'label':2, 'value':1, 'suit':'CLUB' } ]
	];
	var i = 0;
	for each(var _user in _player) {
		//_user_card[_user.getPlayerIndex()] = _user_poker[i];
		_user_card[_user.getPlayerIndex()] = _poker.deal(2); //從撲克實例中取出兩張撲克牌
		i++;
	}
	/*var _pub_card = [
		{'label':9, 'value':8, 'suit':'CLUB' },
		{'label':9, 'value':8, 'suit':'DIAMOND' },
		{'label':'Q', 'value':11, 'suit':'SPADE' },
		{'label':'Q', 'value':11, 'suit':'CLUB' },
		{'label':'k', 'value':12, 'suit':'DIAMOND' }	
	];*/			
	var _result = { pub:_pub_card, pri:_user_card };		
	return _result;
}


/**
 * 初始房間遊戲
 * 玩家牌，5張公共牌，莊家，玩家隊列
 * @access public
 * @param r_room
 */
gameEvent.prototype.formatPokerGame = function(r_room) {			
	var _banker = r_room.getVariable("banker");  //莊家位置
	var _index_arr = r_room.properties.get("indexArr");		
	var _sit_len = _index_arr.length;
	//設置莊家座位index在indexArr中的索引
	var _banker_obj = { };
	if ( _banker == undefined) {
		_banker = 0;
	}else {
		_banker = parseInt(_banker.value) +1 ;
		_banker = ( _banker >= _sit_len) ? (_banker - _sit_len ) : _banker;				
	}	
	var _blinds = parseInt(r_room.getVariable("minBlind").value);			
	
	//小盲注玩家座位
	var _temp_blind = parseInt(_banker) + 1;
	var _small_blind = ( _temp_blind >= _sit_len) ? (_temp_blind - _sit_len ) : _temp_blind;						
	
	//大盲注玩家座位
	_temp_blind = parseInt(_banker) + 2;		
	var _big_blind = ( _temp_blind < _sit_len) ? _temp_blind : (_temp_blind - _sit_len );			
	
	setRoomVariable(r_room, { news:_index_arr[_big_blind] , banker:_banker, index:_big_blind }, false);	
	
	var _params = { };
	_params._cmd = "gameInfo";		
	var _info = { };
	var _small_user = r_room.getUserByPlayerIndex(_index_arr[_small_blind]);
	var _big_user = r_room.getUserByPlayerIndex(_index_arr[_big_blind]);
	_info['banker'] = parseInt(r_room.getUserByPlayerIndex(_index_arr[_banker]).getName());
	_info['max'] = parseInt(_big_user.getName());
	_info['min'] = parseInt(_small_user.getName());
	_params.dataObj = _info;
	//发送布局游戏的基本信息	
	_server.sendResponse(_params, -1, null, r_room.getAllUsers(), 'json');							
	var _poker = this.getRoomPoker(r_room);	
	//扑克类中提取会员的牌
	var _user_poker = _poker.pri;
	//本局的公公牌
	var _pub_poker = _poker.pub;
	//记录公共牌
	r_room.properties.put("pubPoker", _pub_poker);
	for each( var _index in _index_arr ) {
		var _user_temp = r_room.getUserByPlayerIndex(_index);
		//初始会员的两张牌
		_user_temp.properties.put("poker", _user_poker[_index]);
		//给每个用户发送自己牌以及公公牌的信息				
		_params._cmd = "deal";
		//发送的参数：我的牌
		_params.dataObj = { poker:this.formatPoker(_user_poker[_index]), uid:parseInt(_user_temp.getName()) };					
		_server.sendResponse(_params, -1, null, [_user_temp], 'json');
	}						
	//判断是否电脑有下大小盲注
	if (_big_user.getVariable("level").value == 100 ) {
		__AIEvent.doBlind(r_room, _big_user, 'big');		
	}else if ( _small_user.getVariable("level").value == 100 ) {
		__AIEvent.doBlind(r_room, _small_user, 'small');		
	}
	
	//大小盲注
	__betEvent.bet(r_room, r_room.getUserByPlayerIndex(_index_arr[_small_blind]), _blinds);
	__betEvent.bet(r_room, r_room.getUserByPlayerIndex(_index_arr[_big_blind]), (_blinds * 2));	
	trace("formatPokerGame");
}		

/**
 * 比較大小分配彩池
 * @param	r_room	需要分配的房間
 * @return	
 */
gameEvent.prototype.allotPot = function(r_room) {	
	var _index_arr = r_room.properties.get("indexArr");
	_index_arr = (_index_arr == null) ? Array() : _index_arr;
	var _allIn = r_room.properties.get("allIn");
	_allIn = (_allIn == null) ? Array() : _allIn;
	var _bet_arr = r_room.properties.get("potArr");//房間彩池數組		
	var _more = _index_arr.length + _allIn.length;
	if (_more == 1) {
		//一个人的游戏
		this.oneGame(r_room);
		return;
	}
	//大家的游戏
	var _log = { };			//日志记录
	var _pub_poker = r_room.properties.get("pubPoker");			
	_log['pri'] = [];
	_log['pub'] = _pub_poker;
	_log['info'] = { rid:r_room.getId(), time:getDate(0) };
	var texas = new texasPoker();	
	var _data = [];
	var _user_max_poker = { };//记录玩家的最大牌待发送
	var _pot_data = [];//记录池底分配情况待发送
	var _win_data = []; //对应池底的赢家ID数组
	var _poker_data = [];//记录赢家的牌待发送到争池底玩家	
	var _poker_data_user = { };//记录已存赢家信息
	for (var j = 0; j < _bet_arr.length; j++ ) {
		var _pot = new pot(_bet_arr[j][0], _bet_arr[j][1]);				
		var _user_arr = _pot._user_arr;
		var _compare_poker = [];
		var _userId_arr = [];
		for each(var _userId in _user_arr) {
			var _user = _server.getUserById(_userId);
			var _sit = _user.getPlayerIndex();
			var _user_poker = _user.properties.get("poker");	
			var _temp = texas.getResult(_user_poker, _pub_poker);
			var _temp_data = { cards:_temp['cards'], result:_temp['result'], key:_userId, uid:parseInt(_user.getName()) };			
			_compare_poker.push(_temp_data);
			_userId_arr.push(parseInt(_user.getName()));
		}
		var _result = texas.compare(_compare_poker);
		//记录每个比牌玩家发送他的最大牌组合		
		for (var i = 1; i < _result.length; i++ ) {		
			var _user_id = _compare_poker[_result[i]]['key'];
			var _user = _server.getUserById(_user_id);
			var _temp_data = { poker:this.formatPoker(_compare_poker[_result[i]]['cards']), uid:parseInt(_user.getName()) };
			_user_max_poker[_user_id] = (_user_max_poker[_user_id] == null) ? _temp_data : _user_max_poker[_user_id];			
			//_param._cmd = "maxPoker";			
			//_param.dataObj = { poker:this.formatPoker(_compare_poker[_result[i]]['cards']), uid:parseInt(_user.getName()) };
			//_server.sendResponse(_param, -1, null, [_user], 'json');
		}
		if (_result == null || _result == undefined) continue;
		//计算筹码
		var _win_user = [];//池底平分数组待进行分池id
		var _pot_user = [];//池底平分数组待发送到客户端（name）
		var _win_pot = _pot._pot;
		if (typeof(_result[0]) == 'object') {			
			//_win_pot = Math.floor((_pot._pot) / (_result[0].length));
			trace("the win pot is " + _win_pot);
			for each( var _win in _result[0]) {
				var _user_id = _compare_poker[_win]['key'];
				var _winer = _server.getUserById(_user_id);
				//返回這個池底的勝利者信息，id，獲得彩金，他的私人牌，他的組合最大牌
				_pot_user.push(parseInt(_winer.getName()));		
				_win_user.push(_user_id);
				if (_poker_data_user[_user_id] == undefined ) {
					_poker_data_user[_user_id] = true;
					_poker_data.push( { uid:parseInt(_winer.getName()), winP:__gameEvent.formatPoker(_compare_poker[_win]['cards']), winT:_compare_poker[_win]['result'], userP: __gameEvent.formatPoker(_winer.properties.get("poker")) } );
				}
			}
		}else {						
			var _user_id = _compare_poker[_result[0]]['key'];
			var _winer = _server.getUserById(_compare_poker[_result[0]]['key']);
			//返回這個池底的勝利者信息，id，獲得彩金，他的私人牌，他的組合最大牌
			_pot_user.push(parseInt(_winer.getName()));			
			_win_user.push(_user_id);
			if (_poker_data_user[_user_id] == undefined) {
				_poker_data_user[_user_id] = true;
				_poker_data.push( { uid:parseInt(_winer.getName()), winP:__gameEvent.formatPoker(_compare_poker[_result[0]]['cards']), winT:_compare_poker[_result[0]]['result'], userP: __gameEvent.formatPoker(_winer.properties.get("poker")) } );
			}
		}
		//_pot_data.push( { pot:_win_pot, uid:_pot_user } );	
		_pot_data.push( _win_pot );	
		_win_data.push(_pot_user );
		__log.show( { pot:_win_pot, uid:_pot_user } );
		_pot.sharePot(_win_user);
		var _log_data = { };
		_log_data['user'] = _compare_poker;
		_log_data['res'] = _result;
		_log_data['pot'] = { };
		//将用户在api中的id存入日志以便追踪用户
		_log_data['pot'][_bet_arr[j][1]] = _userId_arr;
		_log['pri'].push(_log_data);
	}
	//发送每个用户的最大牌
	for (var v in _user_max_poker) {
		var _param = { };
		_param._cmd = "maxPoker";
		_param.dataObj = _user_max_poker[v];
		_server.sendResponse(_param, -1, null, [_server.getUserById(parseInt(v))], 'json');
	}
	var _params = { };
	_params._cmd = "allotPot";
	_params.dataObj = [_pot_data, _win_data, _poker_data];	
	_server.sendResponse(_params, -1, null, r_room.getAllUsers(), 'json');
	//为该局游戏记录结果
	__log.write('game', _log);
	this.gameOver(r_room);
}
/**
 * 一个人比赛的情况：全部
 * 
 */
gameEvent.prototype.oneGame = function(r_room) {
	var _bet_arr = r_room.properties.get("potArr");//房間彩池數組		
	var _index_arr = r_room.properties.get("indexArr");
	_index_arr = (_index_arr == null) ? Array() : _index_arr;
	var _allIn = r_room.properties.get("allIn");
	_allIn = (_allIn == null) ? Array() : _allIn;
	var _player = (_index_arr.length == 0 ) ? _allIn[0] : _index_arr[0];
	var _pot = parseInt(r_room.getVariable("pot").value);
	var _total_pot = 0;
	var _winer = r_room.getUserByPlayerIndex(_player);
	if (_bet_arr != null) {
		for each( var _pot in _bet_arr) {						
			_total_pot += _pot[1];
		}
	}
	_total_pot += parseInt(r_room.getVariable("pot").value);
	var _bank = parseInt(_winer.getVariable("bank").value);
	_bank = _bank + _total_pot;
	setUserVars(_winer, { bank:_bank } );
	var _params = { };
	_params._cmd = "onegamer";
	_params.dataObj = { uid:parseInt(_winer.getName()), chip:_total_pot };
	_server.sendResponse(_params, -1, null, r_room.getAllUsers(), 'json');
	this.gameOver(r_room);
	return;
}
/**
 *發放和底牌 
 * @param r_room	房間實體
 */
gameEvent.prototype.reDeals = function(r_room) {
	trace("gameEvent reDeals");
	var _deals = parseInt(r_room.getVariable("deals").value);
	if ( _deals > 0 ) {
		var _param = { };				
		var _pub_poker = r_room.properties.get("pubPoker");					
		var _pot_arr;//池底
		var _pot_param = []; //池底数据
		var _index_arr = r_room.properties.get("indexArr");
		var _fold = r_room.properties.get("fold");
		var _allIn = r_room.properties.get("allIn");
		_fold = (_fold == undefined) ? [] : _fold;
		_allIn = (_allIn == undefined) ? [] : _allIn;
		_index_arr = (_index_arr == null) ? Array() : _index_arr;
		if (_index_arr.length <= 1 && _allIn.length > 0) {
			var _begin = (_deals == 1) ? 0 : (_deals+1);
			_deals = 10;//有玩家allin，同时只有一个玩家跟注			
		}else if (_index_arr.length == 1 && _fold.length>0 ) {
			_deals = 11;//只有一个玩家没弃牌
		}
		trace("the deals is " + _deals);
		
		switch(_deals) {	//公共牌
			case 1:
				_pot_arr = __betEvent.formatPot(r_room);
				_pub_poker = _pub_poker.slice(0, 3);
				for each(var _pot in _pot_arr) {
					_pot_param.push(_pot[1]);
				}
				_param._cmd = "comCards";
				//_param.dataObj = { poker:this.formatPoker(_pub_poker) , pot:_pot_param };
				_param.dataObj = { poker:this.formatPoker(_pub_poker)};
				_server.sendResponse(_param, -1, null, r_room.getAllUsers(), 'json');
				break;
			case 2:
			case 3:
				_pot_arr = __betEvent.formatPot(r_room);
				for each(var _pot in _pot_arr) {
					_pot_param.push(_pot[1]);
				}
				_param._cmd = "comCards";
				//_param.dataObj = { poker:this.formatPoker(_pub_poker[(1 + _deals)]) , pot:_pot_param };						
				_param.dataObj = { poker:this.formatPoker(_pub_poker[(1 + _deals)]) };						
				_server.sendResponse(_param, -1, null, r_room.getAllUsers(), 'json');
				break;
			case 10:
				//allIn导致牌局提起结束
				_pot_arr = __betEvent.formatPot(r_room);
				for each(var _pot in _pot_arr) {
					_pot_param.push(_pot[1]);
				}
				_param._cmd = "comCards";
				_pub_poker = _pub_poker.slice(_begin,5);
				//_param.dataObj = { poker:this.formatPoker(_pub_poker), pot:_pot_param };
				_param.dataObj = { poker:this.formatPoker(_pub_poker)};
				_server.sendResponse(_param, -1, null, r_room.getAllUsers(), 'json');
				__gameEvent.allotPot(r_room);
				return "over";
				break;
			default:
				//玩家都弃牌，只剩一个玩家
				_pot_arr = __betEvent.formatPot(r_room);
				for each(var _pot in _pot_arr) {
					_pot_param.push(_pot[1]);
				}
				_param._cmd = "comCards";
				//_param.dataObj = { poker:[] , pot:_pot_param };
				_param.dataObj = { poker:[]  };
				_server.sendResponse(_param, -1, null, r_room.getAllUsers(), 'json');
				__gameEvent.allotPot(r_room);
				return "over";
				break;
		}
	}
	var _next = __userEvent.getNextUserBet(r_room, parseInt(r_room.getVariable("banker").value));
	trace("next is "+_next);
	var _index_arr = r_room.properties.get("indexArr");
	setRoomVariable(r_room, { deals:parseInt(_deals + 1) , news:_index_arr[_next], index: -1 } , false);			
	__userEvent.userEventTime(r_room,_next);
}
/**
 * 扑克牌初始成传输层数据['牌型，花色'，。。。。。]
 */
gameEvent.prototype.formatPoker = function(r_poker) {
	var _poker_type = { SPADE:0, HEART:1, CLUB:2, DIAMOND:3 };
	var _new_poker = [];			
	if ( r_poker.length == undefined) {
		_new_poker.push(r_poker['label'] + "," + _poker_type[r_poker['suit']]);						
	}else {
		for each(var _poker in r_poker) {
			_new_poker.push(_poker['label'] + "," + _poker_type[_poker['suit']]);						
		}
	}
	return _new_poker;			
}

/**
 * 发送池底数据
 */
gameEvent.prototype.sendPotData = function(r_room) {
	var _pot_param = [];
	var _param = { };
	var _pot_arr = __betEvent.formatPot(r_room);
	for each(var _pot in _pot_arr) {
		_pot_param.push(_pot[1]);
	}
	_param._cmd = "potList";
	_param.dataObj = {pot:_pot_param };						
	_server.sendResponse(_param, -1, null, r_room.getAllUsers(), 'json');
}

/**
 * 正常情况下检查游戏是否可以天前结束
 */
gameEvent.prototype.checkGameOver = function(r_room) {
	if (parseInt(r_room.getVariable("state").value) == 2) {
		var _index_arr = r_room.properties.get("indexArr");
		_index_arr = (_index_arr == null) ? Array() : _index_arr;		
		var _allIn = r_room.properties.get("allIn");
		_allIn = (_allIn == null) ? Array() : _allIn;
		//游戏提前结束
		if (_index_arr.length <= 1) {
			if (_allIn.length > 0) {
				this.reDeals(r_room);
			}else {
				this.allotPot(r_room);				
			}
		}
	}
	return false;
}	


gameEvent.prototype.saveData = function() {
	var _player = r_room.getAllPlayers();  //獲取游戲玩家
	var _
	for each(var _user in _player) {
		
		_user_card[_user.getPlayerIndex()] = _poker.deal(2); //從撲克實例中取出兩張撲克牌
	} 
}

/**
 * 房間遊戲結束
 */
gameEvent.prototype.gameOver = function(r_room) {
	__roomEvent.setRoomLeave(r_room);		
	__sys.gc();
	__roomEvent.setInterval(r_room, 'game', 8);	
	trace("gameover and start later");
}
